package com.tfswx.fljdmxyy.validation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.charset.StandardCharsets;

/**
 * 此长度计算方式，一个英文1个长度，一个中文3个长度
 *
 * @author ricky
 * @date 2021/11/30
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MaxLength.Validator.class)
public @interface MaxLength {
    int value();

    String message() default "{path}-数值长度不能超过{value}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class Validator implements ConstraintValidator<MaxLength, Object> {
        private int value;

        @Override
        public void initialize(MaxLength constraintAnnotation) {
            value = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return true;
            }
            String s = value.toString();
            int length = s.getBytes(StandardCharsets.UTF_8).length;
            boolean b = length <= this.value;
            if (!b) {
                ValidUtil.setDefaultParam(context);
            }
            return b;
        }
    }
}
